﻿using HslCommunication.ModBus;
using JinYuan.CommunicationLib.Enum;
using JinYuan.DataConvertLib;
using JinYuan.Helper;
using JinYuan.MES.Models;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using PLCCommunication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JinYuan.ControlCenters
{
    public partial class ControlCenter
    {
        #region 刷新12小时产能
        public void Refresh12HourProdQty()
        {
            List<Chart12HourData> chart12Hours = new List<Chart12HourData>();
            int j = 0;
            int m = 0;
            int n = 0;
            DateTime dtTime = DateTime.Now;
            string strDate = dtTime.ToString("yyyy-MM-dd");
            int Hour = GetHour();
            var listTotal = CommonMethods.db.QueryWhereList<Hourprod>(t => t.FDate == strDate);// 查询稼动率表中total数据
            if (listTotal != null && listTotal.Count > 0)
            {
                for (int i = 1; i < 13; i++)
                {
                    #region X轴数据

                    if (CommonMethods.strClass != "白班")
                    {
                        j = i + 21;

                        if (j >= 25 && j < 26)
                        {
                            m = j - 2;
                            n = j - 25;
                        }
                        else if (j >= 26)
                        {
                            m = j - 26;
                            n = j - 25;
                        }
                        else
                        {
                            m = j - 2;
                            n = j - 1;
                        }
                    }
                    else
                    {
                        j = i + 9;
                        m = j - 2;
                        n = j - 1;
                    }
                    #endregion

                    int Fhour = Convert.ToInt32(m);
                    var hour1 = listTotal.Where(p => p.FHour == Fhour).FirstOrDefault();
                    int ProdALLQty = 0;
                    int ProdOKQty = 0;
                    int ProdNGQty = 0;
                    string strOkRatio = "0.00";

                    if (hour1 != null)
                    {
                        ProdALLQty += hour1.ProdIn;
                        ProdOKQty += hour1.ProdOut;
                    }

                    ProdNGQty = ProdALLQty - ProdOKQty;
                    if (ProdOKQty >= 0 && ProdALLQty > 0)
                    {
                        strOkRatio = (Math.Round(decimal.Parse(ProdOKQty.ToString()) / decimal.Parse(ProdALLQty.ToString()), 4)).ToString();
                    }
                    else
                    {
                        strOkRatio = "0.00";
                    }

                    chart12Hours.Add(new Chart12HourData()
                    {
                        DisplayTime = m + ":30~" + (n) + ":30",
                        ProdIn = ProdALLQty,
                        ProdOut = ProdOKQty,
                        ProdNg = ProdNGQty,
                        OKRatio = strOkRatio
                    });
                }
            }
            else
            {
                for (int i = 1; i < 13; i++)
                {
                    #region X轴数据

                    if (CommonMethods.strClass != "白班")
                    {
                        j = i + 21;

                        if (j >= 25 && j < 26)
                        {
                            m = j - 2;
                            n = j - 25;
                        }
                        else if (j >= 26)
                        {
                            m = j - 26;
                            n = j - 25;
                        }
                        else
                        {
                            m = j - 2;
                            n = j - 1;
                        }

                    }
                    else
                    {
                        j = i + 9;
                        m = j - 2;
                        n = j - 1;
                    }
                    #endregion

                    Random rand = new Random();
                    int ranOK = rand.Next(1000, 3000);
                    int ranNG = rand.Next(400, 1200);
                    int total = ranOK + ranNG;

                    chart12Hours.Add(new Chart12HourData()
                    {
                        DisplayTime = m + ":30~" + n + ":30",
                        ProdIn = ranOK + ranNG,
                        ProdOut = ranOK,
                        ProdNg = ranNG,
                        OKRatio = (Math.Round(decimal.Parse(ranOK.ToString()) / decimal.Parse(total.ToString()) * 0.01m, 2) * 100).ToString()
                    });
                }

            }


            if (chart12Hours != null)
            {
                CommonMethods.Lst_Prod12HourData = chart12Hours;
            }
        }


        public int GetHour()
        {
            DateTime now = DateTime.Now;
            int nowHour = Convert.ToInt32($"{now.Hour}30");
            int hour = 0;
            if (CommonMethods.LastHour != nowHour)
            {
                hour = Convert.ToInt32($"{now.Hour - 1}30");
                if (now.Hour == 0)
                {
                    hour = 2330;
                }
            }
            else
            {
                hour = Convert.ToInt32($"{now.Hour}30");
            }
            return hour;
        }


        #endregion

        #region 检测项不良
        /// <summary>
        /// 读取检测项不良
        /// </summary>
        private void GetDefectTypeQty()
        {

            try
            {
                if (CommonMethods.Lst_DefectTypeQty.Count <= 0)
                {
                    //CommonMethods.Lst_DefectTypeQty.Add(new ChartDataType { DataType = "极性检测不良", DataCount = 0 });
                    //CommonMethods.Lst_DefectTypeQty.Add(new ChartDataType { DataType = "称重不良", DataCount = 0 });
                    //CommonMethods.Lst_DefectTypeQty.Add(new ChartDataType { DataType = "铜极耳剪切不良", DataCount = 0 });
                    //CommonMethods.Lst_DefectTypeQty.Add(new ChartDataType { DataType = "铝极耳剪切不良", DataCount = 0 });

                    CommonMethods.Lst_DefectTypeQty.Add(new ChartDataType { DataType = "扫码不良", DataCount = 0 });
                    CommonMethods.Lst_DefectTypeQty.Add(new ChartDataType { DataType = "MES不良", DataCount = 0 });
                    CommonMethods.Lst_DefectTypeQty.Add(new ChartDataType { DataType = "其他不良", DataCount = 0 });

                }
                else //读取PLC数据
                {
                    if (CommonMethods.plcDevice != null && CommonMethods.plcDevice.IsConnected)
                    {
                        Task.Run(() =>
                        {
                            try
                            {
                                int ProdDRFIDNgQty = CommonMethods.PlcLink.ReadInt16("D1000");//扫码不良
                                int ProdDXNgQty = CommonMethods.PlcLink.ReadInt16("D1001");//MES不良
                                int ProdGRFIDNgQty = CommonMethods.PlcLink.ReadInt16("D1002");//其他不良

                                ////從PLC讀取數據賦值給到NGList
                                //CommonMethods.Lst_DefectTypeQty.Where(p => p.DataType == "极性检测不良").FirstOrDefault().DataCount = ProdDRFIDNgQty;
                                //CommonMethods.Lst_DefectTypeQty.Where(p => p.DataType == "称重不良").FirstOrDefault().DataCount = ProdDXNgQty;
                                //CommonMethods.Lst_DefectTypeQty.Where(p => p.DataType == "铜极耳剪切不良").FirstOrDefault().DataCount = ProdGRFIDNgQty;
                                //CommonMethods.Lst_DefectTypeQty.Where(p => p.DataType == "铝极耳剪切不良").FirstOrDefault().DataCount = ProdYLZNgQty;
                                //從PLC讀取數據賦值給到NGList
                                CommonMethods.Lst_DefectTypeQty.Where(p => p.DataType == "扫码不良").FirstOrDefault().DataCount = ProdDRFIDNgQty;
                                CommonMethods.Lst_DefectTypeQty.Where(p => p.DataType == "MES不良").FirstOrDefault().DataCount = ProdDXNgQty;
                                CommonMethods.Lst_DefectTypeQty.Where(p => p.DataType == "其他不良").FirstOrDefault().DataCount = ProdGRFIDNgQty;
                            }
                            catch (Exception ex)
                            {
                                LoggerHelp.WriteEX(ex);
                            }
                        });

                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelp.WriteEX(ex);
            }
        }
        #endregion

        #region 智能电表 ---默认D1100开始
        public void GetEnergyData()
        {
            ModbusRtu busRtuClient = new ModbusRtu();
            if (CommonMethods.plcDevice != null && CommonMethods.plcDevice.IsConnected)
            {

                List<ElectricEnergy> listM = new List<ElectricEnergy>();
                List<float> ListF = new List<float>();
                List<string> listAddre = new List<string>()
                {
                    "D1100","D1102","D1104","D1106","D1108","D1110","D1112","D1114","D1116","D1118","D1120","D1122","D1124","D1126"
                };
                try
                {
                    busRtuClient.SerialPortInni(sp =>
                    {
                        sp.PortName = "COM1";
                        sp.BaudRate = 9600;
                        sp.DataBits = 8;
                        sp.StopBits = System.IO.Ports.StopBits.One;
                        sp.Parity = System.IO.Ports.Parity.None;
                    });
                    busRtuClient.DataFormat = HslCommunication.Core.DataFormat.CDAB;
                    busRtuClient.Open(); // 打开
                    if (busRtuClient.IsOpen())
                    {
                        // 读取数据
                        HslCommunication.OperateResult<byte[]> readResult = busRtuClient.Read("35", 30);
                        HslCommunication.OperateResult<byte[]> readResult1 = busRtuClient.Read("3", 2);
                        if (readResult.IsSuccess && readResult1.IsSuccess)
                        {
                            //DPT
                            Byte DptH = busRtuClient.ByteTransform.TransByte(readResult.Content, 0);//高8位
                            Byte DptL = busRtuClient.ByteTransform.TransByte(readResult.Content, 1);//低8位
                            //DPQ
                            Byte DpqH = busRtuClient.ByteTransform.TransByte(readResult.Content, 2);//高8位
                            Byte DpqL = busRtuClient.ByteTransform.TransByte(readResult.Content, 3);//低8位

                            ElectricEnergy m = new ElectricEnergy();
                            Decimal q = busRtuClient.ByteTransform.TransUInt16(readResult.Content, 56);
                            Decimal w = busRtuClient.ByteTransform.TransUInt16(readResult.Content, 58);

                            m.pt = Convert.ToDecimal(busRtuClient.ByteTransform.TransInt16(readResult1.Content, 0)); //电压变比 D1124
                            m.ct = Convert.ToDecimal(busRtuClient.ByteTransform.TransInt16(readResult1.Content, 2));  //电流变比 D1126
                            Decimal Power = (q * 65536 + w) / 1000;
                            m.AccumulatedElectricity = Convert.ToDecimal(Power * m.pt * m.ct);   //有功电能（累计电能）D1100
                            ListF.Add((float)m.AccumulatedElectricity.Value);
                            //电压
                            m.PhaseVoltageA = Convert.ToDecimal(busRtuClient.ByteTransform.TransUInt16(readResult.Content, 4) * Math.Pow(10, DptH - 4)); //A相电压 D1102
                            m.PhaseVoltageB = Convert.ToDecimal(busRtuClient.ByteTransform.TransUInt16(readResult.Content, 6) * Math.Pow(10, DptH - 4));//B相电压 D1104
                            m.PhaseVoltageC = Convert.ToDecimal(busRtuClient.ByteTransform.TransUInt16(readResult.Content, 8) * Math.Pow(10, DptH - 4));//C相电压 D1106
                            ListF.Add((float)m.PhaseVoltageA.Value);
                            ListF.Add((float)m.PhaseVoltageB.Value);
                            ListF.Add((float)m.PhaseVoltageC.Value);

                            //电流
                            m.PhaseCurrentA = Convert.ToDecimal(busRtuClient.ByteTransform.TransUInt16(readResult.Content, 16) * Math.Pow(10, DptL - 4)); //电流IA D1108
                            m.PhaseCurrentB = Convert.ToDecimal(busRtuClient.ByteTransform.TransUInt16(readResult.Content, 18) * Math.Pow(10, DptL - 4));//电流IB D1110
                            m.PhaseCurrentC = Convert.ToDecimal(busRtuClient.ByteTransform.TransUInt16(readResult.Content, 20) * Math.Pow(10, DptL - 4));//电流IC D1112
                            ListF.Add((float)m.PhaseCurrentA.Value);
                            ListF.Add((float)m.PhaseCurrentB.Value);
                            ListF.Add((float)m.PhaseCurrentC.Value);

                            //有功功率
                            m.PhasePowerA = Convert.ToDecimal(busRtuClient.ByteTransform.TransInt16(readResult.Content, 22) * Math.Pow(10, DpqH - 4)); //A相有功功率 D1114
                            m.PhasePowerB = Convert.ToDecimal(busRtuClient.ByteTransform.TransInt16(readResult.Content, 24) * Math.Pow(10, DpqH - 4)); //B相有功功率 D1116
                            m.PhasePowerC = Convert.ToDecimal(busRtuClient.ByteTransform.TransInt16(readResult.Content, 26) * Math.Pow(10, DpqH - 4));//C相有功功率 D1118
                            m.ActivePower = Convert.ToDecimal(busRtuClient.ByteTransform.TransInt16(readResult.Content, 28) * Math.Pow(10, DpqH - 4)); //总有功功率 D1120
                            ListF.Add((float)m.PhasePowerA.Value);
                            ListF.Add((float)m.PhasePowerB.Value);
                            ListF.Add((float)m.PhasePowerC.Value);
                            ListF.Add((float)m.ActivePower.Value);
                            m.PowerFactor = Convert.ToDecimal(busRtuClient.ByteTransform.TransInt16(readResult.Content, 44)) / 1000; //总功率因数 D1122
                            ListF.Add((float)m.PowerFactor.Value);
                            ListF.Add((float)m.pt.Value);
                            ListF.Add((float)m.ct.Value);

                            for (int i = 0; i < ListF.Count; i++)
                            {
                                CommonMethods.PlcLink.WriteFloat(listAddre[i], ListF[i]);
                            }
                            listM.Add(m);
                            CommonMethods.listElectricEnergy = listM;

                        }
                        else
                        {
                            TxtHelper.WriteTxt($@"D:\APILog\Logs\智能电表信息\{DateTime.Now.ToString("yyyy-MM-dd")}.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "智能电表:读取数据失败");
                        }
                    }
                    else
                    {
                        TxtHelper.WriteTxt($@"D:\APILog\Logs\智能电表信息\{DateTime.Now.ToString("yyyy-MM-dd")}.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "智能电表：串口打开失败");
                    }
                }
                catch (Exception ex)
                {
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\智能电表信息\{DateTime.Now.ToString("yyyy-MM-dd")}.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + $"智能电表:{ex}");
                }
                finally
                {
                    if (busRtuClient.IsOpen())
                    {
                        busRtuClient.Close();
                    }
                }

            }
        }

        /// <summary>
        /// 能耗上传MES
        /// </summary>
        public void UploadEquEnergy()
        {
            if (CommonMethods.listElectricEnergy.Count > 0)
            {
                if (CommonMethods.mesConfig.isUpMes)
                {
                    string msg = string.Empty;
                    DateTime nowDate = DateTime.Now;
                    string filePath = string.Empty;
                    string fileName = string.Empty;
                    string fileTitle = string.Empty;
                    string fileContent = string.Empty;
                    List<WattrMeter> listP = new List<WattrMeter>();
                    int i = 0;
                    foreach (ElectricEnergy m in CommonMethods.listElectricEnergy)
                    {
                        WattrMeter param = new WattrMeter();
                        param.siteCode = CommonMethods.mesConfig.siteCode;
                        param.lineCode = CommonMethods.mesConfig.lineCode;
                        param.equipNum = CommonMethods.mesConfig.equipNum;
                        param.userName = CommonMethods.mesConfig.mesUserName;
                        param.electricMeterNum = CommonMethods.mesConfig.electricMeterNum[i];
                        param.recordDate = nowDate.ToString("yyyy-MM-dd HH:mm:ss");
                        param.accumulatedElectricity = (decimal)m.AccumulatedElectricity;
                        param.phaseVoltageA = (decimal)m.PhaseVoltageA;
                        param.phaseVoltageB = (decimal)m.PhaseVoltageB;
                        param.phaseVoltageC = (decimal)m.PhaseVoltageC;
                        param.phaseCurrentA = (decimal)m.PhaseCurrentA;
                        param.phaseCurrentB = (decimal)m.PhaseCurrentB;
                        param.phaseCurrentC = (decimal)m.PhaseCurrentC;
                        param.phasePowerA = (decimal)m.PhasePowerA;
                        param.phasePowerB = (decimal)m.PhasePowerB;
                        param.phasePowerC = (decimal)m.PhasePowerC;
                        param.activePower = (decimal)m.ActivePower;
                        param.powerFactor = (decimal)m.PowerFactor;
                        param.pt = (decimal)m.pt;
                        param.ct = (decimal)m.ct;

                        listP.Add(param);
                        i++;

                        // 写csv文件
                        string productName = string.Empty;

                        filePath = $@"{CommonMethods.strWattrMeterpath}\{nowDate.Year}\{nowDate.Month}";
                        fileName = $@"{nowDate.Day}.csv";
                        fileTitle = "工序名称,生产机台编号,拉线,型号,物料编号,操作人员,班次,电表编号,采集时间,有功电能（累计电能）KwH,A相电压 V,B相电压 V,C相电压 V,A相电流 A,B相电流 A,C相电流 A,A相功率 Kw,B相功率 Kw,C相功率 Kw,总有功功率 Kw,总功率因数 %,电压变比,电流变比";
                        fileContent = $"外观检工序,{CommonMethods.mesConfig.equipNum},{CommonMethods.mesConfig.lineCode},{productName},{CommonMethods.mesConfig.MaterialCode},{CommonMethods.mesConfig.mesUserName},{CommonMethods.strClass},{param.electricMeterNum},{nowDate.ToString("yyyy-MM-dd HH:mm:ss")}," +
                            $"{param.accumulatedElectricity},{param.phaseVoltageA},{param.phaseVoltageB},{param.phaseVoltageC},{param.phaseCurrentA},{param.phaseCurrentB},{param.phaseCurrentC}," +
                            $"{param.phasePowerA},{param.phasePowerB},{param.phasePowerC},{param.activePower},{param.powerFactor},{param.pt},{param.ct}";
                        CSVHelper<object>.WriterCSV(filePath, fileName, fileTitle, fileContent);
                    }
                    //上传MES
                    string Mesage = "";
                    bool b = CommonMethods.hbgMes.UploadEquEnergy(CommonMethods.mesConfig.WattrMeterUrl, CommonMethods.mesConfig.equipNum, CommonMethods.mesConfig.siteCode, CommonMethods.mesConfig.lineCode,
                    CommonMethods.mesConfig.mesUserName, CommonMethods.mesConfig.electricMeterNum, listP, ref Mesage);
                }
            }
        }
        #endregion

        /// <summary>
        /// 风速仪数据采集
        /// </summary>
        public void UPloadAnemograph()
        {
            int _anemometerNumber = 34;//风速仪的个数
            string _anemometerAddress = "D15000";//风速仪起始地址
            if (CommonMethods.mesConfig.isUpMes)
            {
                JYResult<byte[]> jYResult = CommonMethods.PlcLink.ReadValue<JYResult<byte[]>>(_anemometerAddress, Data_Type.ArrByte, 150);
                List<float> _anemograph = GetList<float>(_anemometerNumber, 0);//初始化列表
                List<string> _anemometerName = new List<string>();
                string _mesage = "";
                for (int i = 0; i < _anemometerNumber; i++)
                {
                    //初始化风速仪名称
                    int _temple = i + 1;
                    string _name = "风速仪" + _temple.ToString();
                    _anemometerName.Add(_name);

                    //解析数据
                    _anemograph[i] = FloatLib.GetFloatFromByteArray(jYResult.Content, i * 4, DataFormat.CDAB);
                }
                //
                // 写csv文件
                string productName = string.Empty;
                string fileName = string.Empty;
                string filePath = string.Empty;
                DateTime nowDate = DateTime.Now;
                string fileTitle = "工序名称,生产机台编号,拉线,型号,物料编号,操作人员,班次,采集时间,";
                string fileContent = $"预焊工序,{CommonMethods.mesConfig.equipNum},{CommonMethods.mesConfig.lineCode},{productName},{CommonMethods.mesConfig.MaterialCode},{CommonMethods.mesConfig.mesUserName},{CommonMethods.strClass},{nowDate.ToString("yyyy-MM-dd HH:mm:ss")},";
                filePath = $@"{CommonMethods.strAnemographpath}\{nowDate.Year}\{nowDate.Month}";
                fileName = $@"{nowDate.Day}.csv";

                for (int j = 0; j < _anemometerNumber; j++)
                {
                    fileTitle = fileTitle + "," + _anemometerName[j];
                    fileContent = fileContent + "," + _anemograph[j];
                }
                CSVHelper<object>.WriterCSV(filePath, fileName, fileTitle, fileContent);



                if (false)//待确认接口
                {
                    string ur = CommonMethods.mesConfig.CollectData;
                    string equipNum = CommonMethods.mesConfig.equipNum;
                    bool isResult = CommonMethods.hbgMes.UploadDeviceCollectData(ur, equipNum, _anemometerName, _anemograph, ref _mesage);
                }

            }
        }

    }
}
